package com.jyw.activity;

import android.annotation.SuppressLint;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jyw.R;
import com.jyw.network.OkHttpManager;
import com.jyw.network.Server;
import com.jyw.pojo.Order;
import com.jyw.utils.DimenUtils;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author simonw
 * @version 1.0
 * @created 2017/1/5
 */

public class OrdersOverActivity extends BaseActivity implements View.OnClickListener {
    private View mContentView, vNone;
    private SwipeRefreshLayout layoutSwipe;
    private RecyclerView recycler;
    private OrdersAdapter mAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_orders_over);

        layoutSwipe = (SwipeRefreshLayout) findViewById(R.id.layout_swipe);
        recycler = (RecyclerView) findViewById(R.id.recycler);
        vNone = findViewById(R.id.v_none);
        findViewById(R.id.iv_back).setOnClickListener(this);

        recycler.setLayoutManager(new LinearLayoutManager(OrdersOverActivity.this));
        recycler.addItemDecoration(new SpacesItemDecoration(DimenUtils.dip2px(OrdersOverActivity.this, 0f),
                DimenUtils.dip2px(OrdersOverActivity.this, 4f)));
        recycler.setAdapter(mAdapter = new OrdersAdapter(null));

        loadData();

        layoutSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadData();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
        }
    }

    class OrdersAdapter extends RecyclerView.Adapter<OrdersAdapter.OrdersHolder> {
        private List<Order> data;

        OrdersAdapter(List<Order> data) {
            this.data = data;
        }

        void swapData(List<Order> data) {
            this.data = data;
            notifyDataSetChanged();
        }

        @SuppressLint("InflateParams")
        @Override
        public OrdersAdapter.OrdersHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new OrdersAdapter.OrdersHolder(LayoutInflater.from(OrdersOverActivity.this).inflate(R.layout.item_orders, null));
        }

        @Override
        public void onBindViewHolder(OrdersAdapter.OrdersHolder holder, int position) {
            holder.tvClass.setText("洗衣");
            holder.tvState0.setText("已接单");
            holder.tvState1.setText("已接单");
            holder.tvOrderId.setText("订单编号： " + data.get(position).getOrder_id());
            holder.tvTime.setText("取件时间： " + data.get(position).getTime());
        }

        @Override
        public int getItemCount() {
            return data == null ? 0 : data.size();
        }

        class OrdersHolder extends RecyclerView.ViewHolder {
            ImageView ivClass;
            TextView tvClass, tvState0, tvState1, tvOrderId, tvTime, tvCancel;

            OrdersHolder(View itemView) {
                super(itemView);
                ivClass = (ImageView) itemView.findViewById(R.id.iv_class);
                tvClass = (TextView) itemView.findViewById(R.id.tv_class);
                tvState0 = (TextView) itemView.findViewById(R.id.tv_state0);
                tvState1 = (TextView) itemView.findViewById(R.id.tv_state1);
                tvOrderId = (TextView) itemView.findViewById(R.id.tv_order_id);
                tvTime = (TextView) itemView.findViewById(R.id.tv_time);
                tvCancel = (TextView) itemView.findViewById(R.id.tv_cancel);
                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });

                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
            }
        }
    }

    private void loadData() {
        Request request = new Request.Builder().
                url(Server.GET_NOT_SUCC_ORDER + "?phone_data=" + getPrefs().getString("phone", "")
                        + "&state_data=1").
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(OrdersOverActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                JSONArray arr;
                final List<Order> orders = new ArrayList<>();
                try {
                    arr = new JSONArray(response.body().string());
                    if (arr.length() == 0) {
                        new AsyncTask<Void, Void, Void>() {
                            @Override
                            protected Void doInBackground(Void... params) {
                                return null;
                            }

                            @Override
                            protected void onPostExecute(Void aVoid) {
                                super.onPostExecute(aVoid);
                                vNone.setVisibility(View.VISIBLE);
                                layoutSwipe.setRefreshing(false);
                            }
                        }.execute();
                    } else {
                        Gson gson = new Gson();
                        for (int i = 0; i < arr.length(); i++) {
                            orders.add(gson.fromJson(arr.get(i).toString(), Order.class));
                        }

                        new AsyncTask<Void, Void, Void>() {
                            @Override
                            protected Void doInBackground(Void... params) {
                                return null;
                            }

                            @Override
                            protected void onPostExecute(Void aVoid) {
                                super.onPostExecute(aVoid);
                                vNone.setVisibility(View.GONE);
                                layoutSwipe.setRefreshing(false);
                                mAdapter.swapData(orders);
                            }
                        }.execute();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    class SpacesItemDecoration extends RecyclerView.ItemDecoration {
        private int leftRight;
        private int topBottom;

        SpacesItemDecoration(int leftRight, int topBottom) {
            this.leftRight = leftRight;
            this.topBottom = topBottom;
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            super.onDraw(c, parent, state);
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
            //竖直方向的
            if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {
                //最后一项需要 bottom
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.bottom = topBottom;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
                outRect.right = leftRight;
            } else {
                //最后一项需要right
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.right = leftRight;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
                outRect.bottom = topBottom;
            }
        }
    }
}
